<template>
    <div class="assessment-page" v-if="pageList.length >= 1">
        <x-header :left-options="{backText: '', preventGoBack: true}"
                  class="gradient-color"
                  @on-click-back="goBackPage">额度评估

        </x-header>
        <p class="tip">请确保录入本人真实信息，否则将影响最终评估结果</p>
        <group>
            <div v-for="(pageItem, index) in pageList"
                 v-if="activePageItem === pageItem"
                 :key="index">
                <div v-for="(item, itemIndex) in questions[pageItem]" :key="itemIndex">
                    <x-input v-if="item.type === 1"
                             :title="item.name"
                             type="tel"
                             :max="7"
                             text-align="right"
                             :novalidate="true"
                             v-model.trim="item.value"
                             :placeholder="'请输入'" class="formItemBorder">
                        <span slot="right" class="unit">元</span>
                    </x-input>
                    <FSheet v-if="item.type === 2"
                            :placeholder="'请选择'"
                            v-model="item.value"
                            :title="item.name"
                            :menus="item.answer" class="formItemBorder">
                    </FSheet>
                    <FSheet v-if="item.type === 3"
                            :placeholder="'请选择'"
                            v-model="item.value"
                            :title="item.name"
                            :menus="item.answer"
                            @on-menu-change="handleMenuChange" class="formItemBorder">
                    </FSheet>
                </div>
            </div>
            <!--追加内容-->
            <div v-if="activePageItem===1">
                <div v-for="(item, itemIndex) in addQuestions" :key="itemIndex">
                    <x-input v-if="item.type === 1"
                             :title="item.name"
                             type="tel"
                             :max="7"
                             class="formItemBorder"
                             text-align="right"
                             v-model.trim="item.value"
                             :novalidate="true"
                             :placeholder="'请输入'">
                        <span slot="right" class="unit">元</span>
                    </x-input>
                    <FSheet v-if="item.type === 2"
                            :placeholder="'请选择'"
                            v-model="item.value"
                            :title="item.name"
                            class="formItemBorder"
                            :menus="item.answer"></FSheet>
                </div>
            </div>
        </group>
        <FButton text="下一步" v-if="!isLastStep" @on-click-button="handleNextStep"></FButton>
        <FButton text="开始评估" v-if="isLastStep" @on-click-button="handleSubmit"></FButton>
    </div>
</template>

<script>
    /**
     * Created by c.y on 2018/3/16.
     * 额度评估首页
     */
    import {XHeader, XInput, Confirm, Group, Selector, XButton} from 'vux';
    import FButton from '../../components/common/FButton.vue';
    import FSheet from '../../components/common/FSheet.vue';
    import systemApi from '../../api/api';
    import statusCodeManage from '../../api/statusCodeManage';
    import validate from '../../tool/validator';

    export default {
        name: 'f-assessment',
        data () {
            return {
                value: 1,
                pageList: [], // 一共有几页
                questions: [], // 问题的总条数
                activePageItem: 0, // 激活当前页
                isLastStep: false, // 是否是最后一步
                addQuestions: '' // 追加的问题列表

            }
        },
        components: {
            XHeader,
            XInput,
            Group,
            FButton,
            Selector,
            FSheet,
            Confirm,
            XButton
        },
        methods: {
            goBackPage () {
                // 如果是第一步的话，那么返回到上一个页面
                if (this.activePageItem <= 1) {
                    this.$router.back();
                    // 不是的话，那么显示上一步
                } else {
                    this.activePageItem--;
                    this.isLastStep = this.pageList.length === this.activePageItem;
                }
            },
            // 获取初始化的问题列表
            fetchQuestionList () {
                systemApi.fetchQuestionAndTypeList().then(response => {
                    this.pageList = response.question.pageList;
                    this.questions = response.question.questions;
                    this.activePageItem = this.pageList[0];
                    // 是否为最后一步
                    this.isLastStep = this.pageList.length <= 1;
                }, error => {
                    statusCodeManage.showTipOfStatusCode(error,this);
                })
            },
            // 选择职业时，改变额外问题的列表
            handleMenuChange (selectVal) {
                let questions = this.getAddQuestions(selectVal.name);
                // 清除上一次选择的数据
                if (questions && questions.length) {
                    questions.forEach(function (item) {
                        if (item.value) {
                            item.value = '';
                        }
                    });
                }
                if (validate.checkValEmpty(questions)) {
                    this.addQuestions = '';
                    return false;
                }
                this.addQuestions = questions;
            },
            // 获取追加的问题列表/或者计算用的系数， name是选择值, 是否返回为系数
            getAddQuestions (name) {
                let questionsList = this.questions[1];
                for (let i = 0; i < questionsList.length; i++) {
                    if (questionsList[i].type === 3) {
                        let answerList = questionsList[i].answer;
                        for (let j = 0; j < answerList.length; j++) {
                            if (answerList[j].name === name) {
                                return answerList[j].childQuestion ? answerList[j].childQuestion : '';
                            }
                        }
                    }
                }
            },
            // 根据类型的不同，进行提示
            checkRequired (checkList) {
                let _this = this;
                let reg = /^[1-9]{1}\d{0,6}$/;
                for (let i = 0; i < checkList.length; i++) {
                    if (checkList[i].type === 1) {
                        if (validate.checkValEmpty(checkList[i].value)) {
                            _this.$vux.toast.text('请输入' + checkList[i].name, 'middle');
                            return false;
                        } else if (!reg.test(checkList[i].value)) {
                            _this.$vux.toast.text('请输入正确的' + checkList[i].name, 'middle');
                            return false;
                        }
                    } else {
                        if (validate.checkValEmpty(checkList[i].value)) {
                            _this.$vux.toast.text('请选择' + checkList[i].name, 'middle');
                            return false;
                        }
                    }
                }
                return true
            },
            // 判断是否必填，并进行提示, checkAdd是否检测额外的内容
            checkNextStepRequired (activeItem, checkAdd = false) {
                // 判读主步骤是否必填
                let checkResult = this.checkRequired(this.questions[activeItem]);
                if (!checkResult) {
                    return false;
                }
                // 判断额外内容是否必填
                if (checkAdd) {
                    let checkAddResult = this.checkRequired(this.addQuestions);
                    if (!checkAddResult) {
                        return false;
                    }
                }
                return true;
            },
            // 点击下一步
            handleNextStep () {
                if (!this.checkNextStepRequired(this.activePageItem, true)) {
                    return false;
                }
                this.activePageItem++;
                this.isLastStep = this.pageList.length === this.activePageItem;
            },
            // 提交
            handleSubmit () {
                if (!this.checkNextStepRequired(this.activePageItem)) {
                    return false;
                }
                // 计算额度评估，并跳转页面
                this.calculateQuota();
            },
            // 合并数据的方法
            integrateData (dataList) {
                let integrateList = [];
                dataList.forEach(function (item) {
                    integrateList.push({
                        questionId: item.id,
                        questionType: item.type,
                        answer: item.value
                    });
                });
                return integrateList;
            },
            // 整合提交到后台数据
            handleIntegrateData () {
                // 问题分为两个列表
                let submitInfo = [];
                submitInfo.push(...this.integrateData(this.questions[1]));
                submitInfo.push(...this.integrateData(this.questions[2]));
                if (this.addQuestions) {
                    submitInfo.push(...this.integrateData(this.addQuestions));
                }
                return submitInfo;
            },
            // 根据选择的name, 得到相应当然计算系数
            getComputedVal (item) {
                if (!(item.answer instanceof Array)) {
                    throw new Error('该下拉的选择列表不是一个数组');
                }
                for (let i = 0; i < item.answer.length; i++) {
                    if (item.value === item.answer[i].name) {
                        return item.answer[i].value;
                    }
                }
                return '';
            },
            // 计算额度
            calculateQuota () {
                // 额度 = 20000*教育程度*职业身份*是否有本地公积金*是否有本地社保*名下房产类型*名下是否有车*您的信用情况
                let _this = this;
                // 计算的结果
                let quotaResult = 20000;
                // 计算依据
                let calList = [];
                // 获取需要计算的数据
                for (let i = 0; i < this.pageList.length; i++) {
                    let qList = this.questions[this.pageList[i]];
                    for (let j = 0; j < qList.length; j++) {
                        if (qList[j].name === '教育程度' ||
                            qList[j].name === '是否有本地公积金' ||
                            qList[j].name === '是否有本地社保' ||
                            qList[j].name === '名下是否有车' ||
                            qList[j].name === '名下房产类型' ||
                            qList[j].name === '您的信用情况' ||
                            qList[j].name === '职业身份'
                        ) {
                            calList.push({
                                name: qList[j].name,
                                value: _this.getComputedVal(qList[j])
                            });
                        }
                    }
                }
                // 额度评估的结果
                calList.forEach(function (item) {
                    quotaResult = Math.floor(quotaResult * item.value);
                });
                let submitInfo = {
                    assessRecVos: _this.handleIntegrateData()
                };
                systemApi.saveAssessmentList(submitInfo).then(response => {
                }, error => {
                    statusCodeManage.showTipOfStatusCode(error,_this);
                });
                this.$router.push({
                    path: '/f-assessment-result',
                    query: {
                        quota: quotaResult
                    }
                });
            }
        },
        activated: function () {
            this.value = 1;
            this.pageList = [];
            this.questions = [];
            this.activePageItem = 0;
            this.isLastStep = false;
            this.addQuestions = '';
            this.fetchQuestionList();
        }
    }
</script>

<style lang="less">
    @import "../../style/mixin";

    .assessment-page {
        background-color: @color-background-default;
        .vux-header {
            .color-linear-gradient(@color-gradient-darkBlue-left, @color-gradient-darkBlue-right);
            .vux-header-title {
                font-size: 18px;
            }
        }
        .tip {
            padding-left: 12px;
            font-size: @font-size-small;
            color: @color-text-third;
            line-height: 32px;
        }
        .weui-cells {
            margin-top: 0;
            font-size: @font-size-base;
            .weui-cell {
                .weui-cell__bd {
                    font-size: @font-size-medium;
                }
            }
        }
        .weui-cells:before {
            display: none;
        }
        .weui-cells:after {
            display: none;
        }
        input::-webkit-input-placeholder {
            color: #999 !important;
        }
        .f-sheet {
            .f-cell {
                padding-left: 0;
                .f-cell-ft {
                    font-size: @font-size-medium;
                    padding-right: 20px;
                }
            }
            .f-cell:after {
                display: none;
            }
        }
        .unit {
            color: @color-text-primary;
            vertical-align: middle;
            padding-left: 5px;
        }
        .f-actionsheet-menu {
            .formItemBorder {
                border-bottom: 1px solid @color-divider-regular;
            }
        }
        .f-button, .weui-btn {
            margin-top: 30px;
            font-size: @font-size-primary;
        }
        .formItemBorder {
            border-bottom: 1px solid @color-background-default;
        }
        .vux-1px-b:after {
            border-color: #ddd;
        }
    }
</style>
